package cn.harvest.storage.bo.admin;

import java.util.List;

import cn.harvest.storage.dao.DAO;
import cn.harvest.storage.po.Employee;

public class OperatorService {

	private DAO dao = DAO.getDAO();

	private OperatorService() {

	}

	public static OperatorService getService() {

		OperatorService service = new OperatorService();
		return service;
	}

	public List selectBySQL(Employee emp) {

		StringBuffer sql = new StringBuffer();
		
		sql.append(" SELECT e.employee_id, e.employee_name, e.operator_name, eem.employment_name");
		sql.append(" FROM employee e, employment eem");
		sql.append(" WHERE 1 = 1");
		sql.append(" AND eem.employment_id = e.employment_id");
		sql.append(" AND e.employee_state = '0'");
		sql.append(" AND e.isOper = '1'");
		if (!(null == emp.getEmployeeName() || "".equals(emp.getEmployeeName()))) {
			sql.append("AND e.employee_name LIKE '%" + emp.getEmployeeName() + "%' ");
		}
		if (!(null == emp.getEmployment() || "".equals(emp.getEmployment().getEmploymentId()))) {
			sql.append("AND e.employment_id = '" + emp.getEmployment().getEmploymentId() + "' ");
		}
		sql.append(" ORDER BY e.employee_id");

		System.out.println("### - OperatorService -> selectBySQL -> #SQL \r\n	 " + sql);
		
		return dao.selectBySQL(sql.toString());
	}
	
	public List selectOperatorInfo(String empId) {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT et.permission_id, per.permission_news");
		sql.append(" FROM employee_item et, permission per");
		sql.append(" WHERE et.permission_id = per.permission_id");
		sql.append(" AND et.employee_id = " + empId);
		sql.append(" ORDER BY et.permission_id");
		
		System.out.println("### - OperatorService -> selectOperatorInfo -> #SQL \r\n	 " + sql);
		
		return dao.selectBySQL(sql.toString());
	}

	public boolean updateOperPerm(String empId,String[] operPerms) {
		StringBuffer deleteSql = new StringBuffer();
		deleteSql.append(" DELETE FROM employee_item WHERE employee_id = " + empId);
		System.out.println("### - OperatorService -> updateOperPerm -> DELETE -> #SQL \r\n	 " + deleteSql);
		boolean delCompleted = dao.deleteBySQL(deleteSql.toString());
		
		int count = 0;
		if (delCompleted && !"".equals(operPerms[0])) {
			for (int i = 0; i < operPerms.length; i++) {
				StringBuffer updateSql = new StringBuffer(" INSERT INTO employee_item (employee_id,permission_id) VALUES ('" + empId + "', '" + operPerms[i] + "')");
				System.out.println("### - OperatorService -> updateOperPerm -> INSERT -> #SQL \r\n	 " + updateSql);
				count = count + dao.updateBySQL(updateSql.toString());
//				updateSql.append(";\r\n	 ");
			}
		} else {
			count = 1;
		}
		boolean updateCompleted = count == operPerms.length;

		return updateCompleted;
	}
	
	public static void main(String[] args) {

	}
}
